package tgc.rj.garbage.utlis;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android_serialport_api.SerialPort;
import tgc.rj.garbage.custom.IConstant;

public class SerialportScanUtils extends Thread {
    private InputStream inputStream = null;
    private SerialPort serialPort = null;
    private OutputStream outputStream = null;
    private Handler handler;
    public Boolean falg = true;

    public SerialportScanUtils(Handler handler) {
        super();
        this.handler = handler;
    }

    public SerialportScanUtils() {
        super();
    }

    @Override
    public void run() {
        while (falg) {
            try {
                byte[] readData = new byte[1024];
                byte[] x = new byte[1024];
                int idx = 0;
                for (int j = 0; j < 2; j++) {
                    Thread.sleep(50);
                    int size = inputStream.read(readData);
                    for (int i = 0; i < size; i++) {
                        x[idx++] = readData[i];
                    }
                    if(idx>=8){
                        break;
                    }
                }
                String str = new String(x, 0, idx);
                Message message = new Message();
                Bundle bundle = new Bundle();
                bundle.putString("data", str);
                message.setData(bundle);
                handler.sendMessage(message);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        serialPort.close();
    }


    public void openSrialPort() {
        try {
            serialPort = new SerialPort(new File("/dev/" + IConstant.PORT2), IConstant.BAUDRATE2, 0);
            //获取打开的串口中的输入输出流，以便于串口数据的收发
            inputStream = serialPort.getInputStream();
            outputStream = serialPort.getOutputStream();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void closeSerialPort() {
        Log.i("test", "关闭串口");
        try {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
            falg = false;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
